package cn.myjerry.server.demo3;

import java.io.IOException;
import java.net.Socket;

public class Dispatcher implements Runnable {
	private Socket client;
	private Request req;
	private Response res;
	private int code = 200;
	
	public Dispatcher(Socket client) {
		this.client = client;
		try {
			req = new Request(client.getInputStream());
			res = new Response(client.getOutputStream());
		} catch (IOException e) {
			this.code = 500;
			return;
		}
	}
	
	@Override
	public void run() {
		try {
			Servlet serv = WebApp.getServlet(req.getUrl());
			if(null == serv) {
				this.code = 404;
			} else {
				serv.service(req, res);
			}
			res.pushToClient(code);
		} catch (Exception e) {
			this.code = 500;
		}
		try {
			res.pushToClient(500);
		} catch (IOException e) {
			e.printStackTrace();
		}
		CloseUtil.closeAll(client);
	}

	

}
